<template>
  <div ref="chartDom" id="chartDom"></div>
</template>

<script>
import * as echarts from 'echarts'
import debounce from 'lodash/debounce'
// import elementResizeDetectorMaker from 'element-resize-detector'
import { addListener, removeListener } from 'resize-detector';

export default {
  name: 'ZChart',
  props: {
    option: {
      type: Object,
      default: () => {}
    }
  },
  watch: {
    option (val) {
			this.chart.clear();
      this.chart.setOption(val, true);
    }
  },
  mounted () {
    this.renderChart();
    this.resize = debounce(this.resize, 300);
    // let erd = elementResizeDetectorMaker();
    // erd.listenTo(document.getElementById('chartDom'), (element) => {
    //   this.resize();
    // });
    addListener(this.$refs.chartDom, this.resize);
  },
  beforeDestroy () {
    removeListener(this.$refs.chartDom, this.resize);
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    resize () {
      if (this.chart) {
        this.chart.resize();
      }
    },
    renderChart () {
      this.chart = echarts.init(this.$refs.chartDom);
      this.chart.setOption(this.option);
			this.chart.on('click', (params) => {
				this.$emit('openDetail',params);
			});
    }
  }
};
</script>
